package com.atguigu.msmservice.service.impl;

import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.HttpUtils;
import com.atguigu.msmservice.utils.RandomUtil;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //短信发送验证吗，templateID仅供测试调用
    public static void main(String[] args) {

    }


    @Override
    public boolean send(String phone) {
        String host = "https://jmsms.market.alicloudapi.com";
        String path = "/sms/send";
        String method = "POST";
        String appcode = "9561e2e1fb3241788029be4a4ca3f96e";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("templateId", "M72CB42894");
        //生成验证码
        querys.put("value", RandomUtil.getFourBitRandom());
        Map<String, String> bodys = new HashMap<String, String>();
        System.out.println("验证码位："+querys.get("value"));

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            redisTemplate.opsForValue().set(phone, querys.get("value"),10, TimeUnit.MINUTES);
            System.out.println(response.toString());
            //获取response的body
//            System.out.println(EntityUtils.toString(((org.apache.http.HttpResponse) response).getEntity()));
            System.out.println(EntityUtils.toString(response.getEntity()));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
